package cn.hengzhu.main_manager.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;

import cn.hengzhu.main_manager.utils.config.xcx.AliConfig;
import cn.hengzhu.main_manager.utils.config.xcx.WxConfig;
import cn.hengzhu.main_manager.utils.httpssl.ClientCustomSSL;

public class WxPayBeforUtil {

	public static Map<String, String> getPayMap(String appid, String MCHID, String nonce_str, String body,
			String out_trade_no, Integer amount, String openId, String notify_url, String time_expire) {
		Map<String, String> payMap = new HashMap<String, String>();
		payMap.put("appid", appid);
		payMap.put("mch_id", MCHID);
		payMap.put("nonce_str", nonce_str);
		payMap.put("body", body);
		payMap.put("out_trade_no", out_trade_no);
		payMap.put("total_fee", String.valueOf(amount));
		payMap.put("spbill_create_ip", "127.0.0.1");
		payMap.put("notify_url", notify_url);
		payMap.put("trade_type", "JSAPI");
		payMap.put("time_expire", time_expire);
		payMap.put("openid", openId);
		return payMap;
	}

	

	public static StringBuffer getPayXml(String appid, String MCHID, String nonce_str, String body,
			String out_trade_no, Integer amount, String openId, String notify_url, String time_expire,String sign) {
		StringBuffer paramBuffer = new StringBuffer();
		paramBuffer.append("<xml>");
		paramBuffer.append("<appid>" + appid + "</appid>");
		paramBuffer.append("<mch_id>" + MCHID + "</mch_id>");
		paramBuffer.append("<nonce_str>" + nonce_str + "</nonce_str>");
		paramBuffer.append("<time_expire>" + time_expire + "</time_expire>");
		paramBuffer.append("<sign>" + sign + "</sign>");
		paramBuffer.append("<body>" + body + "</body>");
		paramBuffer.append("<out_trade_no>" + out_trade_no + "</out_trade_no>");
		paramBuffer.append("<total_fee>" + amount + "</total_fee>");
		paramBuffer.append("<spbill_create_ip>" + "127.0.0.1" + "</spbill_create_ip>");
		paramBuffer.append("<notify_url>" + notify_url + "</notify_url>");
		paramBuffer.append("<trade_type>" + "JSAPI" + "</trade_type>");
		paramBuffer.append("<openid>" + openId + "</openid>");
		paramBuffer.append("</xml>");
		return paramBuffer;
	}

	public static StringBuffer getPayXml(String appid, String MCHID, String nonce_str, String body,
										 String out_trade_no, Integer amount, String openId, String notify_url, String time_expire,Integer priceId,String sign) {
		StringBuffer paramBuffer = new StringBuffer();
		paramBuffer.append("<xml>");
		paramBuffer.append("<appid>" + appid + "</appid>");
		paramBuffer.append("<mch_id>" + MCHID + "</mch_id>");
		paramBuffer.append("<nonce_str>" + nonce_str + "</nonce_str>");
		paramBuffer.append("<time_expire>" + time_expire + "</time_expire>");
		paramBuffer.append("<sign>" + sign + "</sign>");
		paramBuffer.append("<body>" + body + "</body>");
		paramBuffer.append("<out_trade_no>" + out_trade_no + "</out_trade_no>");
		paramBuffer.append("<total_fee>" + amount + "</total_fee>");
		paramBuffer.append("<spbill_create_ip>" + "127.0.0.1" + "</spbill_create_ip>");
		paramBuffer.append("<notify_url>" + notify_url + "</notify_url>");
		paramBuffer.append("<trade_type>" + "JSAPI" + "</trade_type>");
		paramBuffer.append("<openid>" + openId + "</openid>");
		paramBuffer.append("<attach>" + "priceId=" + priceId + "</attach>");
		paramBuffer.append("</xml>");
		return paramBuffer;
	}



	/**
	 * 微信退款
	 * @param assureTransactionId 订单号
	 * @param totalFee 订单总金额
	 * @param refundFee 退款金额
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	public static Map<String,String> wxRefund(String assureTransactionId,int totalFee,int refundFee) throws UnsupportedEncodingException, Exception{
		String appid = WxConfig.APPID;
		String MCHID = WxConfig.MCH_ID;
		String KEY = WxConfig.KEY;
		Date date = new Date();
		String nonce_str = DictionaryUtils.getRandomStr();
		String out_refund_no = "tk" + date.getTime() + nonce_str.substring(0, 2);

		Map<String, String> map = new HashMap<>();
		map.put("appid", appid);
		map.put("mch_id", MCHID);
		map.put("nonce_str", nonce_str);
		map.put("transaction_id", assureTransactionId);
		map.put("out_refund_no", out_refund_no);
		map.put("total_fee", String.valueOf(totalFee));
		map.put("refund_fee", String.valueOf(refundFee));
		map.put("refund_account", "REFUND_SOURCE_RECHARGE_FUNDS");
		map.put("notify_url", WxConfig.DOMAIN_URL + "/xcx/backPayNotify");
		String stringA = DictionaryUtils.formatUrlMap(map, false, false);
		String stringSignTemp = stringA + "&key=" + KEY;
		String sign = Md5Util.wxXcxHash(stringSignTemp).toUpperCase();

		StringBuffer paramBuffer = new StringBuffer();
		paramBuffer.append("<xml>");
		paramBuffer.append("<appid>" + appid + "</appid>");
		paramBuffer.append("<mch_id>" + MCHID + "</mch_id>");
		paramBuffer.append("<nonce_str>" + nonce_str + "</nonce_str>");
		paramBuffer.append("<sign>" + sign + "</sign>");
		paramBuffer.append("<transaction_id>" + assureTransactionId + "</transaction_id>");
		paramBuffer.append("<out_refund_no>" + out_refund_no + "</out_refund_no>");
		paramBuffer.append("<total_fee>" + String.valueOf(totalFee) + "</total_fee>");
		paramBuffer.append("<refund_fee>" + String.valueOf(refundFee) + "</refund_fee>");
		paramBuffer.append("<refund_account>" + "REFUND_SOURCE_RECHARGE_FUNDS" + "</refund_account>");
		paramBuffer.append("<notify_url>" + WxConfig.DOMAIN_URL + "/xcx/backPayNotify" + "</notify_url>");
		paramBuffer.append("</xml>");
		
		String postData = ClientCustomSSL.postData(WxConfig.BACKPAY_URL,new String(paramBuffer.toString().getBytes(), "ISO8859-1"));

		InputStream is = new ByteArrayInputStream(postData.getBytes());
		InputStreamReader isReader = new InputStreamReader(is, "utf-8");
		Map<String, String> xmlMap = XmlPullUtil.parse(isReader);
		return xmlMap;
	}
	
	/**
	 * 支付宝退款
	 * @param assureTransactionId 订单号
	 * @param totalAmount 退款金额
	 * @return
	 * @throws AlipayApiException
	 */
	public static AlipayTradeRefundResponse aliRefund(String assureTransactionId,BigDecimal totalAmount) throws AlipayApiException{
		String random = UUID.randomUUID().toString().replaceAll("-", "");
		AlipayClient alipayClient = new DefaultAlipayClient(AliConfig.URL, AliConfig.APP_ID, AliConfig.PRIVATE_KEY, "json", "UTF-8", AliConfig.ALIPAY_PUBLIC_KEY, "RSA2");
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("trade_no", assureTransactionId);
		paramMap.put("refund_amount", totalAmount);
		paramMap.put("out_request_no", random);
		paramMap.put("refund_reason", "退款");
		String jsonString = JSONObject.toJSONString(paramMap);
		request.setBizContent(jsonString);
		AlipayTradeRefundResponse response = alipayClient.execute(request);
		return response;
	}
	

}
